//
//  DMNetworkMonitor.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/9/4.
//

#import "DMNetworkMonitor.h"
#import <AFNetworking/AFNetworking.h>

@interface DMNetworkMonitor ()
@property (nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
@property (nonatomic, assign, readwrite) DMNetworkStatus currentStatus;
@end

@implementation DMNetworkMonitor

+ (instancetype)sharedManager {
    static DMNetworkMonitor *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMNetworkMonitor alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _reachabilityManager = [AFNetworkReachabilityManager sharedManager];
        _currentStatus = DMNetworkStatusUnknown;
    }
    return self;
}

- (void)startMonitoring {
    __weak typeof(self) weakSelf = self;
    [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        __strong typeof(weakSelf) self = weakSelf;
        DMNetworkStatus mappedStatus = DMNetworkStatusUnknown;
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                mappedStatus = DMNetworkStatusNotReachable;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                mappedStatus = DMNetworkStatusWWAN;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                mappedStatus = DMNetworkStatusWiFi;
                break;
            default:
                mappedStatus = DMNetworkStatusUnknown;
                break;
        }
        self.currentStatus = mappedStatus;

        // 打印日志
        NSLog(@"[Network] 当前网络状态: %ld", (long)mappedStatus);

        // 回调到外部
        if (self.networkStatusChanged) {
            self.networkStatusChanged(mappedStatus);
        }
    }];
    [self.reachabilityManager startMonitoring];
}

- (void)stopMonitoring {
    [self.reachabilityManager stopMonitoring];
}

@end
